const api = require('../../utils/api');

Page({
  data: {
    dessert: null,
    loading: true,
    error: false,
    steps: []
  },

  onLoad: function(options) {
    const id = options.id;
    if (!id) {
      this.setData({
        loading: false,
        error: true
      });
      
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }
    
    this.loadDessertDetail(id);
  },
  
  // 加载甜点详情
  loadDessertDetail: function(id) {
    this.setData({ loading: true, error: false });
    
    api.getDessertDetail(id)
      .then(data => {
        // 处理制作步骤，将文本分割为数组
        const steps = this.processInstructions(data.instructions);
        
        this.setData({
          dessert: data,
          steps: steps,
          loading: false
        });
      })
      .catch(err => {
        console.error('加载甜点详情失败:', err);
        this.setData({
          loading: false,
          error: true
        });
        
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },
  
  // 处理制作步骤，将文本分割为数组
  processInstructions: function(instructions) {
    if (!instructions) return [];
    
    // 按数字编号或换行符分割
    return instructions.split(/\d+\.\s|\n/).filter(step => step.trim() !== '');
  },
  
  // 返回上一页
  onBackTap: function() {
    wx.navigateBack();
  },
  
  onShareAppMessage: function() {
    const dessert = this.data.dessert;
    if (!dessert) return {};
    
    return {
      title: `【甜点食谱】${dessert.name}`,
      path: `/pages/detail/detail?id=${dessert.id}`
    };
  }
}); 